// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  let nowDate = new Date()
  nowDate.setDate(nowDate.getDate() + 5)

  let res = {
    toEndCount: 0,
    outDateCount: 0
  }
  const _ = db.command
  let toEndCount = await db.collection('thing').where({
    endDate: _.gte(new Date().getTime()).and(_.lte(nowDate.getTime())),
    bcheck:true,
    _openid: wxContext.OPENID
  }).count();

  let outDateCount = await db.collection('thing').where({
    endDate: _.lt(getDate(new Date()).getTime()),
    bcheck:true,
    _openid: wxContext.OPENID
  }).count();

  res.toEndCount = toEndCount.total
  res.outDateCount = outDateCount.total
  return res
}

function getDateFormat(date) {
  return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
}

function getDate(date) {
  var year = date.getFullYear()
  var month = date.getMonth()
  var day = date.getDate()
  var nDate = new Date(year, month, day)
  console.log(new Date(nDate).getTime())
  return nDate
}